"""
报名
"""
from decimal import Decimal
import json
from django.db import transaction
import logging

from common.models import TbGames, TbMiniappUser, TbOrders, TbGameApply
from src.utils import wx, dataTool, record

errlog = logging.getLogger("err")


class ApplyDirector:
    def __init__(self):
        self.pa = wx.PayAgent()
        self.gr = record.GameRecord()
        self.gar = record.GameApplyRecord()
        self.order_r = record.OrderRecord()

    def pay_apply_price(self, **kwargs):
        """
        支付报名费用
        """
        # 取参
        # --- start ---
        game_id = kwargs.get("game_id")
        apply_id = kwargs.get("apply_id")
        user: TbMiniappUser = kwargs.get("user")

        # --- end ---
        with transaction.atomic():
            # 准备参数
            game: TbGames = self.gr.get_record(game_id)
            out_trade_no = self.pa.order_num()  # 订单号
            time_expire = dataTool.DateTimeTool().get_after_half_hour()
            time_expire_str = dataTool.DateTimeTool(datetime_obj=time_expire).get_rfc_datetime_str()
            description = "师资保证金缴纳"
            currency = "CNY"
            price = game.apply_price
            attach = json.dumps({
                "apply_id": apply_id
            })
            # 保存订单
            order_info = {
                "total_price": price,
                "pay_price": 0,
                "time_expire": time_expire_str,
                "out_trade_no": out_trade_no,
                "description": description,
                "attach": attach,
                "currency": currency,
                "pay_status": 0,
                "payer_id": user.uid,
                "symbol": "-",
            }
            self.order_r.create_record(**order_info)
            # 支付
            pay_info = {
                "description": description,
                "out_trade_no": out_trade_no,
                "notify_url": "/teacher/securityDepositPaySucess",
                "amount": int(price * 100),
                "openid": user.mini_openid,
                "time_expire": time_expire_str,
                "currency": currency,
                "attach": attach
            }
            result = self.pa.pay(**pay_info)
            result["out_trade_no"] = out_trade_no
            return result

    def get_pay_result(self, **kwargs):
        """
        查询报名结果
        """
        result = self.pa.get_pay_result(**kwargs)
        return result

    def apply_pay_success(self, **kwargs):
        """
        报名支付成功
        """
        out_trade_no = kwargs.get("out_trade_no")
        order: TbOrders = self.order_r.get_record_condition(out_trade_no=out_trade_no)
        attach = json.loads(order.attach)
        apply_id = attach.get("apply_id")
        apply: TbGameApply = self.gar.get_record(apply_id)
        with transaction.atomic():
            # 订单记录
            order.pay_price = 0
            order.pay_status = 1
            order.save()
            # 支付成功记录
            apply.is_payed = 1
            apply.save()
            result = self.gar.record_obj_serializer(apply)
            return result

    def apply(self, **kwargs):
        """
        赛事报名
        """
        game_id = kwargs.get("game_id")
        name = kwargs.get("name")
        phone = kwargs.get("phone")
        address = kwargs.get("address")
        # 验证
        # --- start ---
        # 验证该赛事是否报名过
        is_exits = self.gar.exits_record(game_id=game_id, phone=phone, is_delete=0)
        if is_exits:
            raise ValueError("已经报名过了")
        # --- end ---
        with transaction.atomic():
            game: TbGames = self.gr.get_record(game_id)
            apply_info = {
                "game_id": game_id,
                "name": name,
                "phone": phone,
                "address": address,
                "need_pay": game.need_pay,
                "is_payed": 0
            }
            game_apply = self.gar.create_record(**apply_info)
            # 修改赛事报名人数
            game.apply += 1
            game.save()
            # 加入讨论组
            return self.gar.record_obj_serializer(game_apply)
